/*
 * DataReader.cpp
 *
 *  Created on: Oct 1, 2010
 *      Author: blyth
 */

#include <SimDataReader.h>
#include <dataForm.h>
#include <TBranch.h>
#include <sstream>
#include <cstring>
#include <iostream>
#include <globals.hh>
using namespace std;

SimDataReader::SimDataReader(char* path, int maxPhotons) :
	maxPhotons(maxPhotons) {
	file = new TFile(path);
	index = -1;
	photon = 0;
	tree = NULL;
	BHVetoBranch = NULL;
	BHVeto = false;
	frontVetoBranch = NULL;
	frontVeto = false;
	rearVetoBranch = NULL;
	rearVeto = false;
	sideVetoBranch = NULL;
	sideVeto = false;
	barrelVetoBranch = NULL;
	barrelVeto = false;
	cout << endl;
}

SimDataReader::~SimDataReader() {
	file->Close();
}

bool SimDataReader::ReadNext(TH2D* hist) {
	if (photon == 0) {
		stringstream* ss = new stringstream;
		index++;
		cout << "\r" << index << flush;
		*ss << "eventNumber" << index;
		tree = (TTree*) file->Get((ss->str()).c_str());
		delete ss;
		if (!tree)
			return false;
		BHVetoBranch = tree->GetBranch("BHVeto");
		BHVetoBranch->SetAddress(&BHVeto);
		frontVetoBranch = tree->GetBranch("frontVeto");
		frontVetoBranch->SetAddress(&frontVeto);
		rearVetoBranch = tree->GetBranch("rearVeto");
		rearVetoBranch->SetAddress(&rearVeto);
		sideVetoBranch = tree->GetBranch("sideVeto");
		sideVetoBranch->SetAddress(&sideVeto);
		barrelVetoBranch = tree->GetBranch("barrelVeto");
		barrelVetoBranch->SetAddress(&barrelVeto);
	}
	BHVetoBranch->GetEvent(photon);
	frontVetoBranch->GetEvent(photon);
	rearVetoBranch->GetEvent(photon);
	sideVetoBranch->GetEvent(photon);
	barrelVetoBranch->GetEvent(photon);
	if (BHVeto || frontVeto || rearVeto || sideVeto || barrelVeto) {
		photon++;
		if (photon >= maxPhotons) {
			photon = 0;
			tree->Delete();
		}
		return this->ReadNext(hist);
	}

	dataForm* data = new dataForm;

	stringstream ss1;
	ss1 << "photonNumber" << photon;
	TBranch* branch = tree->GetBranch((ss1.str()).c_str());
	branch->SetAddress(data);

	int count = branch->GetEntryNumber();
	for (int j = 0; j < count; j++) {
		branch->GetEntry(j);
		hist->Fill((data->x) / m, (data->y) / m, data->energy);
	}

	delete data;

	photon++;
	if (photon >= maxPhotons) {
		photon = 0;
		tree->Delete();
	}
	return true;
}
